//#define _BSD_SOURCE
#include <stdint.h>
#include "sysfs.h"
#include "stat.h"
#include <string.h>

#define abs(a, b) (((a) > (b)) ? ((a) - (b)) : ((b) - (a)))


int get_cpu(cpu_t *cpu)
{
    char buf[16 * 1024] = {0};
    cputime_t now;

    get_str("/proc/stat", buf, sizeof(buf) - 1);

    char *p = buf;
    char *line = strsep(&p, "\n"); // pass first line "cpu "

    int i = 0;
    while ((line = strsep(&p, "\n")) != NULL) {
        // got a line "cpu0"

        char *row_ptr = line;
        char *col = strsep(&row_ptr, " "); // pass first col. "cpu0"

        if (strstr(col, "cpu") == NULL)
            break;

        int j = 0;
        uint64_t total_now = 0;
        uint64_t total_old = 0;
        while ((col = strsep(&row_ptr, " ")) != NULL) {
            if (j >= 7)
                break;
            now.value[j] = atoll(col);
            total_now += now.value[j];
            total_old += cpu[i].old.value[j];
            j++;
        }

        uint64_t total_diff = abs(total_now, total_old);
        uint64_t idle_diff  = abs(now.idle, cpu[i].old.idle);

        cpu[i].usage = (total_diff - idle_diff) * 100.0 / total_diff;
        cpu[i].old = now;

        i++;
    }

    return i; // cpu numbers
}

